<?php
declare (strict_types = 1);

namespace app\common\command;

use app\common\model\Product;
use app\common\model\ProductCategory;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

class AmountScheme extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('amount-scheme')
            ->setDescription('商品数量计划方案');
    }

    protected function execute(Input $input, Output $output)
    {

        $filter = [
            'is_deleted' => ProductCategory::NO_DELETED,
            'status' => ProductCategory::ENABLED_STATUS
        ];
        $categoryIdArr = ProductCategory::field(['id'])->where($filter)->column('id');
        if(empty($categoryIdArr)) {
            $output->writeln('无商品分类');
            return;
        }

        $filter = [
            'is_deleted' => Product::NO_DELETED,
            'status' => Product::ENABLED_STATUS,
            'amount_scheme' => Product::ENABLED_AMOUNT_SCHEME,
            'cate_id' => $categoryIdArr,
        ];

        $products = Product::where($filter)
            ->where('amount', '>', 0)
            ->where('rand_num', '>', 0)
            ->where('remain_num', '>', 0)
            ->select();
        if(!$products) {
            $output->writeln('无商品');
            return;
        }

        foreach ($products as $productItem) {
            $flag = false;
            if(empty($productItem->start_time)) {
                if(empty($productItem->end_time)) {
                    $flag = true;
                }else{
                    if(time() <= strtotime($productItem->end_time)) $flag = true;
                }
            }else{
                $st = strtotime($productItem->start_time);
                if(time() >= $st) {
                    if(empty($productItem->end_time)) {
                        $flag = true;
                    }else {
                        $et = strtotime($productItem->end_time);
                        $max = max($st, $et);
                        if(time() <= $max) $flag = true;
                    }
                }
            }

            if($flag) {
                $randNum = mt_rand(0, $productItem->rand_num);
                if($productItem->amount >= $randNum && $productItem->remain_num >= $randNum) {
                    $productItem->amount -= $randNum;
                    $productItem->remain_num -= $randNum;
                }else{
                    $productItem->amount -= $productItem->remain_num;
                    $productItem->remain_num = 0;
                }
            }

            $productItem->save();
        }

        // 指令输出
        $output->writeln('执行完成!');
    }
}
